/*
 * Copyright (c) 2017, www.zm0618.com All Rights Reserved..
 */

package com.light.hessian.remoting.client.balance;

import com.light.hessian.provider.config.ProviderStatus;
import com.light.hessian.provider.slot.ProviderStatusSlot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by zhaojun on 2017/02/12.
 */
public class RandomBalancer extends BaseBalancer{
    protected static  final Logger logger= LoggerFactory.getLogger(RandomBalancer.class);

    protected final AtomicLong counter=new AtomicLong(0);//访问次数计数位

    private final Random random=new Random();

    public RandomBalancer() {

    }

    public RandomBalancer(List<ProviderStatusSlot> statusSlots) {
        this.setProviderStatusSlots(statusSlots);
    }

    @Override
    public void setProviderStatusSlots(List<ProviderStatusSlot> statusSlots) {
        super.setProviderStatusSlots(statusSlots);
    }

    @Override
    public String getBalancerName() {
        return Balance.random.name();
    }

    @Override
    public ProviderStatusSlot select() {
        ProviderStatusSlot[] cStatusSlots = statusSlots;
        int len = cStatusSlots.length;
        int index=random.nextInt(len);
        ProviderStatusSlot statusSlot = cStatusSlots[index];
        if (statusSlot.isShowBalancer()){
            logger.info("=====>{}",statusSlot);
        }
        if (statusSlot.getStatus()== ProviderStatus.UP){
            return statusSlot;
        }
        return failback(index,cStatusSlots);
    }





}
